package com.sanjiayi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanjiayi.mapper.FollowMapper;
import com.sanjiayi.mapper.UserMapper;
import com.sanjiayi.pojo.Follow;
import com.sanjiayi.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class FollowServiceImpl implements FollowService {

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public boolean toggleFollow(Integer followerId, Integer followedId) {
        // 不能关注自己
        if (followerId.equals(followedId)) {
            throw new RuntimeException("不能关注自己");
        }

        // 检查用户是否存在
        if (userMapper.selectById(followedId) == null) {
            throw new RuntimeException("被关注的用户不存在");
        }

        // 检查是否已关注
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", followerId)
                   .eq("followed_id", followedId);
        Follow existingFollow = followMapper.selectOne(queryWrapper);

        if (existingFollow != null) {
            // 已关注，取消关注
            followMapper.delete(queryWrapper);
            return false;
        } else {
            // 未关注，添加关注
            Follow follow = new Follow();
            follow.setFollowerId(followerId);
            follow.setFollowedId(followedId);
            follow.setCreateTime(new Date());
            followMapper.insert(follow);
            return true;
        }
    }

    @Override
    public boolean hasFollowed(Integer followerId, Integer followedId) {
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", followerId)
                   .eq("followed_id", followedId);
        return followMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public List<Follow> getFollowingList(Integer userId) {
        return followMapper.getFollowingList(userId);
    }

    @Override
    public List<Follow> getFollowerList(Integer userId) {
        return followMapper.getFollowerList(userId);
    }

    @Override
    public int getFollowingCount(Integer userId) {
        Integer count = followMapper.getFollowingCount(userId);
        return count != null ? count : 0;
    }

    @Override
    public int getFollowerCount(Integer userId) {
        Integer count = followMapper.getFollowerCount(userId);
        return count != null ? count : 0;
    }
} 